<template>
  <div>
    <div class="top-box">
      <router-link to="/admin/news/editor"><el-button type="success">发布新闻</el-button></router-link>
      <router-link to="/admin/news/video/detail"><el-button type="success">发布视频</el-button></router-link>
      <router-link to="/admin/news/member/detail"><el-button type="success">添加成员</el-button></router-link>
    </div>
    <div class="user pd">
      <div class="search-box">
        <el-input v-model="title" placeholder="标题" class="user-input"></el-input>
        <el-select v-model="isPublish" placeholder="是否发布" class="user-input">
          <el-option
            v-for="item in status_list"
            :key="item.id"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
        <!--是否为精选的选项-->
        <el-select v-model="isRecommend" placeholder="是否为精选" class="user-input">
          <el-option
            v-for="item in recommendOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
        <!--是否为类目精选的选项-->
        <el-select v-model="isCategoryRecommend" placeholder="是否为类目精选" class="user-input">
          <el-option
            v-for="item in categoryRecommendOption"
            :key="item.id"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
        <!--是否为导航推荐的选项-->
        <el-select v-model="isNavRecommend" placeholder="是否为导航推荐" class="user-input">
          <el-option
            v-for="item in navRecommendOption"
            :key="item.id"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
        <el-select v-model="firstLevelCid" placeholder="一级分类" filterable  class="cycle-input"  @change="changeFirstLevel">
          <el-option key="" label="请选择一级分类" value=""></el-option>
          <el-option
            v-for="item in categoryList"
            :key="item.id"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
        <el-select v-model="secondLevelCid" placeholder="二级分类" filterable  class="cycle-input"  @change="changeSecondLevel">
          <el-option key="" label="请选择二级分类" value=""></el-option>
          <el-option
            v-for="item in secondLevelCategoryList"
            :key="item.id"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
        <!--<el-input v-model="author" placeholder="作者" class="user-input"></el-input>
        <el-input v-model="source" placeholder="来源" class="user-input"></el-input>-->
        <el-date-picker
          v-model="timeRange"
          type="daterange"
          placeholder="发布时间范围">
        </el-date-picker>
        <el-button type="primary" class="el-icon-search" @click="search">搜索</el-button>
        <el-button class="el-icon-q" @click="repeal">撤销</el-button>
      </div>
      <el-table :data="listData.list" v-loading.body="listLoadingFlag" element-loading-text="拼命加载中" stripe border fit highlight-current-row style="width: 100%;margin-top: 30px" max-height="700">
        <el-table-column label="ID" prop="id" style="width:50px;"></el-table-column>
        <el-table-column label="标题" prop="title"></el-table-column>
        <el-table-column label="一级分类" prop="first_level_cname"></el-table-column>
        <el-table-column label="二级分类" prop="second_level_cname"></el-table-column>
        <el-table-column label="新闻类型" prop="type_name"></el-table-column>
        <el-table-column label="浏览量" prop="views"></el-table-column>
        <!--<el-table-column label="点赞量" prop="agree_count"></el-table-column>-->
        <el-table-column label="所属专题" prop="subject_name"></el-table-column>
        <el-table-column label="封面图">
          <template scope="scope">
            <img :src="scope.row.cover_path" class="art-cover" @click="previewImg(scope.row.cover_path)">
          </template>
        </el-table-column>
        <el-table-column label="发布时间" prop="repub_time"></el-table-column>
        <el-table-column label="排序值" prop="sort"></el-table-column>
        <el-table-column label="是否为精选">
          <template scope="scope">
            <div class="input-group-box">
              <el-switch
                v-model="scope.row.is_top"
                on-text="是"
                off-text="否"
                @change="changeTop($event, scope.row.id, scope.row.title, scope.$index)">
              </el-switch>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="是否发布">
          <template scope="scope">
            <div class="input-group-box">
              <el-switch
                v-model="scope.row.status"
                on-text="是"
                off-text="否"
                @change="changePublish($event, scope.row.id, scope.row.title, scope.$index)">
              </el-switch>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="是否类目推荐">
          <template scope="scope">
            <div class="input-group-box">
              <el-switch
                v-model="scope.row.is_recommend"
                on-text="是"
                off-text="否"
                @change="changeRecommend($event, scope.row.id, scope.row.title, scope.$index)">
              </el-switch>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="是否导航推荐">
          <template scope="scope">
            <div class="input-group-box">
              <el-switch
                v-model="scope.row.is_nav_recommend"
                on-text="是"
                off-text="否"
                @change="changeNavRecommend($event, scope.row.id, scope.row.title, scope.$index)">
              </el-switch>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right"  width="100" align="center">
          <template scope="scope">
            <i class="i-icon icon-check" title="预览" @click="previewNews(scope.row.id, scope.row.publish_time)"></i>
            <i class="i-icon icon-revamp" title="修改" @click="updateNews(scope.row.id, scope.row.type)"></i>
            <i class="i-icon icon-delete" title="删除" @click="deleteNews(scope.row.id)"></i>
          </template>
        </el-table-column>
      </el-table>
      <div v-show="!listLoadingFlag" class="pagination-container">
        <el-pagination
          @current-change="handleCurrentChange"
          :current-page.sync="pageall"
          :page-size="pageSize"
          layout="total, prev, pager, next, jumper"
          :total="listData.total">
        </el-pagination>
      </div>
    </div>
    <preview  v-if="isPreview" :priviewObject="priviewObject" v-on:isCloseView="closeView"></preview>
    <el-dialog
      title="查看封面图"
      :visible.sync="imgVisible"
      :before-close="handleClose"
      size="tiny">
      <img :src="imgUrl" style="width:100%">
    </el-dialog>
    <div class="art-fade" v-if="loadPreview">
      <load></load>
    </div>
  </div>
</template>
<script>
  import api from '../../utils/api'
  import apiConfig from '../../utils/apiconfig'
  import helper from '../../utils/helper'
  import crypt from '../../utils/crypto-helper-pkcs7'
  import formatdate from '../../utils/formatdate.js'
  import preview from './preview'
  import load from '../../components/loading'
  export default {
    data () {
      return {
        status_list: [
          {
            id: '',
            name: '全部发布状态'
          },
          {
            id: 1,
            name: '已发布'
          },
          {
            id: 0,
            name: '未发布'
          }
        ],
        recommendOptions: [
          {
            id: '',
            name: '全部精选状态'
          },
          {
            id: 1,
            name: '已精选'
          },
          {
            id: 0,
            name: '未精选'
          }
        ],
        categoryRecommendOption: [
          {
            id: '',
            name: '全部类目精选状态'
          },
          {
            id: 1,
            name: '已设置'
          },
          {
            id: 0,
            name: '未设置'
          }
        ],
        navRecommendOption: [
          {
            id: '',
            name: '全部导航推荐状态'
          },
          {
            id: 1,
            name: '已设置导航推荐'
          },
          {
            id: 0,
            name: '未设置导航推荐'
          }
        ],
        title: '',
        isPublish: '',
        isRecommend: '',
        isCategoryRecommend: '',
        isNavRecommend: '',
        timeRange: '',
        author: '',
        source: '',
        categoryList: [],
        secondLevelCategoryList: [],
        category: '',
        firstLevelCid: '',
        secondLevelCid: '',
        page: 1,
        pageall: 1,
        listData: {},
        listLoadingFlag: true,
        pageSize: 20,
        imgVisible: false,
        imgUrl: '',
        isPreview: false,
        loadPreview: false
      }
    },
    components: {
      preview,
      load
    },
    created () {
      // 获取缓存的的参数和默认显示的部分（全部、未开始、进行中等）
      var param = window.sessionStorage.getItem('params')
      if (param !== null && param !== '') {
        let paramst = param.replace(/ /g, '+')
        let paramstring = crypt.decrypt(paramst)
        let paramJson = JSON.parse(paramstring)

        this.page = paramJson.page
        this.pageall = paramJson.page
        this.isPublish = paramJson.status
        this.title = paramJson.title
        this.author = paramJson.author
        this.source = paramJson.source
        this.firstLevelCid = paramJson.first_level_cid
        this.secondLevelCid = paramJson.second_level_cid
        this.start_time = paramJson.start_time
        this.end_time = paramJson.end_time
        this.isRecommend = paramJson.is_top
        this.isCategoryRecommend = paramJson.is_recommend
        this.isNavRecommend = paramJson.is_nav_recommend
        let secondLevelOptionsEncode = window.sessionStorage.getItem('secondLevelCategoryList')
        secondLevelOptionsEncode = secondLevelOptionsEncode.replace(/ /g, '+')
        let secondLevelOptionsDecode = crypt.decrypt(secondLevelOptionsEncode)
        let secondLevelOptionJson = JSON.parse(secondLevelOptionsDecode)
        this.secondLevelCategoryList = secondLevelOptionJson
      }
      this.getCategoryLevelOption()
      this.getlist()
      var that = this
      document.onkeydown = function (event) {
        var e = event || window.event
        if (e && e.keyCode === 13) {
          that.search()
        }
      }
    },
    methods: {
      search () {
        this.getlist()
      },
      repeal () {
        this.title = ''
        this.isPublish = ''
        this.author = ''
        this.source = ''
        this.timeRange = ''
        this.firstLevelCid = ''
        this.secondLevelCid = ''
        this.isRecommend = ''
        this.isCategoryRecommend = ''
        this.isNavRecommend = ''
      },
      getCategoryLevelOption () {
        var param = {
          param: ''
        }
        api.GET(helper.getManageApiUrl(apiConfig.newsCategoryAllLevel), param, res => {
          this.categoryList = res
        }, res => {
          console.log(res)
        })
      },
      getSearchParams () { // 参数
        var param = {
          page: this.page,
          status: this.isPublish,
          title: this.title,
          author: this.author,
          source: this.source,
          first_level_cid: this.firstLevelCid,
          second_level_cid: this.secondLevelCid,
          start_time: formatdate(this.timeRange[0]),
          end_time: formatdate(this.timeRange[1]),
          is_recommend: this.isCategoryRecommend,
          is_top: this.isRecommend,
          is_nav_recommend: this.isNavRecommend
        }
        this.params = param
      },
      getlist () {
        this.listLoadingFlag = true
        this.getSearchParams()
        api.GET(helper.getManageApiUrl(apiConfig.newsList), this.params, res => {
          this.listData = res
          var list = this.listData.list
          list.forEach((item, index) => {
            if (item.is_top === 0) {
              item.is_top = false
            } else {
              item.is_top = true
            }
            if (item.status === 0) {
              item.status = false
            } else {
              item.status = true
            }
            if (item.is_recommend === 0) {
              item.is_recommend = false
            } else {
              item.is_recommend = true
            }
            if (item.is_nav_recommend === 0) {
              item.is_nav_recommend = false
            } else {
              item.is_nav_recommend = true
            }
          })
          this.listLoadingFlag = false
        }, res => {
          console.log(res)
        })
      },
      handleCurrentChange (val) {
        this.page = val
        this.getlist()
      },
      changeFirstLevel (val) {
        this.secondLevelCategoryList = []
        this.firstLevelCid = val
        this.categoryList.forEach((item) => {
          if (item.id === val) {
            this.secondLevelCategoryList = item.list
          }
        })
      },
      changeSecondLevel (val) {
        this.secondLevelCid = val
      },
      previewImg (cover) {
        this.imgUrl = cover
        this.imgVisible = true
      },
      handleClose () {
        this.imgUrl = ''
        this.imgVisible = false
      },
      previewNews (id, time) { // 文章预览
        this.loadPreview = true
        var param = {
          id: id
        }
        api.GET(helper.getManageApiUrl(apiConfig.newsDetail), param, res => {
          let resData = res
          this.priviewObject = {
            title: resData.title,
            author: resData.author,
            source: resData.source,
            newsDetail: resData.content,
            published_time: time
          }
          this.isPreview = true
          this.loadPreview = false
        }, res => {
          console.log(res)
        })
      },
      closeView () {
        this.isPreview = false
      },
      updateNews (id, type) { // 修改文章
        var secondLevelCateList = JSON.stringify(this.secondLevelCategoryList)
        var sparam = crypt.encrypt(secondLevelCateList)
        window.sessionStorage.setItem('secondLevelCategoryList', sparam)

        let paramjson = JSON.stringify(this.params)
        let sparams = crypt.encrypt(paramjson)
        window.sessionStorage.setItem('params', sparams)
        let url = '/admin/news/editor?id=' + id
        if (type === 1) {
          url = '/admin/news/video/detail?id=' + id
        } else if (type === 2) {
          url = '/admin/news/member/detail?id=' + id
        }
        this.$router.push(url)
      },
      deleteNews (id) { // 删除文章
        var param = {
          id: id
        }
        this.$confirm('确认要删除此条信息吗？')
          .then(_ => {
            api.GET(helper.getManageApiUrl(apiConfig.deleteNews), param, res => {
              this.$notify({
                title: '成功',
                message: '删除成功',
                type: 'success',
                duration: 1500
              })
              this.getlist()
            }, res => {
              this.$notify({
                title: '失败',
                message: '删除失败',
                type: 'error',
                duration: 1500
              })
            })
          })
          .catch(_ => {})
      },
      changeTop (event, id, title, index) {
        var tip = event === true ? '确定将新闻“' + title + '”设置为精选吗' : '确定取消精选新闻“' + title + '”吗？'
        var param = {
          id: id,
          is_top: event === true ? 1 : 0
        }
        this.changeStatus(param, tip, () => {
          this.listData.list[index].is_top = !event
        })
      },
      changeRecommend (event, id, title, index) {
        var tip = event === true ? '确定设置新闻“' + title + '”为类目推荐吗' : '确定取消新闻“' + title + '”的类目推荐吗？'
        var param = {
          id: id,
          is_recommend: event === true ? 1 : 0
        }
        this.changeStatus(param, tip, () => {
          this.listData.list[index].is_recommend = !event
        })
      },
      changeNavRecommend (event, id, title, index) {
        var tip = event === true ? '确定设置新闻“' + title + '”为导航推荐吗' : '确定取消新闻“' + title + '”的导航推荐吗？'
        var param = {
          id: id,
          is_nav_recommend: event === true ? 1 : 0
        }
        this.changeStatus(param, tip, () => {
          this.listData.list[index].is_nav_recommend = !event
        })
      },
      changePublish (event, id, title, index) {
        var tip = event === true ? '确定立即发布“' + title + '”吗？' : '确定取消发布“' + title + '”吗？'
        var param = {
          id: id,
          status: event === true ? 1 : 0
        }
        this.changeStatus(param, tip, () => {
          this.listData.list[index].status = !event
        })
      },
      changeStatus (param, tip, fn) {
        this.$confirm(tip)
          .then(_ => {
            api.GET(helper.getManageApiUrl(apiConfig.updateNewsState), param, res => {
              this.$notify({
                title: '成功',
                message: '操作成功',
                type: 'success',
                duration: 1500
              })
              this.getlist()
            }, res => {
              this.$notify({
                title: '失败',
                message: res.msg,
                type: 'error',
                duration: 1500
              })
            })
          }).catch(_ => {
            typeof fn === 'function' && fn()
          })
      }
    }
  }
</script>
<style>
  .search-box {
    font-size: 0;
  }
  .search-box .user-input{
    width: 197px;
    margin: 3px 2px;
  }
  .art-cover {
    width: 95px;
    height: 70px;
  }
  .art-fade {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 99;
    background: rgba(255, 255, 255, 0.7);
    padding-top: 5%;
  }
</style>

